package net.javalib.gvmax.post.server.util;

import java.io.BufferedReader;
import java.io.StringReader;

import javax.mail.internet.MimeMessage;

public class SMSExtractor {
	
	public static SMS getSMS(MimeMessage message) throws Exception {
		SMS sms = new SMS();
		sms.number = extractSMSNumber(message.getSubject());
		sms.contact = extractSMSContact(message.getSubject());
		if (sms.contact == null)
			sms.contact = sms.number;

		sms.text = "";
    	// Extract smsText (note special support for beejive media links)
		String emailText = MiscUtil.getEmailText(message);
   		BufferedReader reader = new BufferedReader(new StringReader(emailText));
   		String line = reader.readLine();
   		while (line != null) {
   			// Special beejive tweek to deal with media content
   			if (line.contains("beejive.com"))
   				line += "  ";
   			else
   				line = line.trim();
   			if (line.equals("--"))
   				break;
   			if (!"".equals(line)) 
   				sms.text += line + "\n";
   			line = reader.readLine();
   		}
   		if (!"".equals(sms.text))
   			sms.text = sms.text.substring(0,sms.text.length()-1);
   		return sms;
	}
	
	private static String extractSMSNumber(String subject) {
		String fromNumber = subject.substring("SMS from ".length());
		int bPos = fromNumber.indexOf('[');
		if ( bPos != -1 ) {
			fromNumber = fromNumber.substring(bPos+1,fromNumber.length()-1);
		}
		return MiscUtil.normalizeNumber(fromNumber);
	}
	
	private static String extractSMSContact(String subject) {
		String from = subject.substring("SMS from ".length());
		int bPos = from.indexOf('[');
		if ( bPos != -1 ) {
			return from.substring(0,bPos).trim();
		}
		return null;
	}
	
}
